﻿using Dapper;
using ERPEF;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [Consumes("application/json")]
    [ApiController]
    public class ProRdersController : ControllerBase
    {
        private readonly MyDbContext myDbContext;

        private readonly pro_NtityService _pro_NtityService;
        
        private readonly pro_OrdersService _pro_OrdersService;

        private readonly bs_clientService _bs_clientService;

        private readonly bs_dict_dataService bs_dict_data;
        public ProRdersController(MyDbContext myDbContext, pro_NtityService pro_NtityService, pro_OrdersService pro_OrdersService ,bs_clientService bs_clientService, bs_dict_dataService bs_Dict_DataService)
        {
            this.myDbContext = myDbContext;
            _pro_NtityService = pro_NtityService;
            _pro_OrdersService = pro_OrdersService;
            _bs_clientService = bs_clientService;
            bs_dict_data = bs_Dict_DataService;
        }

        /// <summary>
        /// 生产订单查询
        /// </summary>
        /// <returns></returns>   
        [HttpGet]
        public async Task<List<pro_orders>> OrdersIdext()
        {

            return await _pro_OrdersService.Query();
        }

        /// <summary>
        ///生产订单添加
        /// </summary>
        /// <returns></returns> 
        [HttpPost]
        public async Task<IActionResult> OrdersAdd([FromBody] pro_orders orders)
        {
            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateWarehouseCode(maxCodeNumber);

            orders.po_number = newCode;


            orders.po_packaging = "散装";

            if (ModelState.IsValid)
            {
                int result = await _pro_OrdersService.Add(orders);
                if (result > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.pro_orders
               .Where(w => w.po_number.StartsWith("SCDD"))
               .Select(w => w.po_number.Substring(5)) // 修改为从第三个字符开始截取
               .OrderByDescending(code => code)
               .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "1";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);

            // 生成新的编码数字部
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了9999，则重置为0001
            if (newCodeNumber > 9999)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }

        // 生成新的编码
        private string GenerateWarehouseCode(int codeNumber)
        {
            // 返回完整的编码，包括前缀 "GYS" 和数字部分
            string code = "SCDD" + codeNumber.ToString("D2");

            // 如果编码超过了列的最大长度，截取适合长度
            int maxLength = 10; // 假设列的最大长度为10，根据实际情况修改
            if (code.Length > maxLength)
            {
                code = code.Substring(0, maxLength);
            }

            return code;
        }

        /// <summary>
        ///生产订单修改
        /// </summary>
        /// <returns></returns> 

        [HttpPut]
        public async Task<IActionResult> OrdersUpdate(pro_orders orders)
        {

            orders.po_packaging = "散装";
            if (ModelState.IsValid)
            {
                orders.pro_ntitie = null;
                int result = await _pro_OrdersService.Update(orders);
                if (result > 0)
                {
                    return Ok("修改成功！");

                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        /// <summary>
        /// 生产订单删除
        /// </summary>
        /// <returns></returns> 

        [HttpDelete("{po_id}")]
        public async Task<string> OrdersDelete(int po_id)
        {
            var model = await myDbContext.pro_orders
                .Include(m => m.pro_ntitie)
                .FirstOrDefaultAsync(m => m.po_id == po_id);

            if (model == null || model.IsDeleted == true)
            {
                return "未找到对应的数据";
            }

            // 检查是否存在未被删除的 bs_Model_From 数据
            var undeletedFroms = model.pro_ntitie.Any(f => f.IsDeleted == false);

            if (undeletedFroms)
            {
                return "存在关联数据，删除失败";
            }

            // 逻辑删除 bs_model 数据
            model.IsDeleted = true;
            await myDbContext.SaveChangesAsync();

            return "删除成功";
        }

        /// <summary>
        /// 客户列表查询
        /// </summary>
        /// <returns></returns>   
        [HttpGet]
        public async Task<List<bs_client>> ClientIndex()
        {

            return await _bs_clientService.Query();
        }

        /// <summary>
        /// 客户属性查询
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        public async Task<IActionResult> Queryclient()
        {
            var warehouse = await bs_dict_data.Queryclient();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }


        /// <summary>
        /// 生产订单分页
        /// </summary>
        /// <returns></returns> 

        [HttpGet]
        public ActionResult<FenYe<pro_orders>> getFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "po_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pro_orders"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pro_orders>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pro_orders> fenYe = new FenYe<pro_orders>()
                {
                    prorders = result,
                    Rows = row,
                };

                if (fenYe.prorders.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }


        /// <summary>
        /// 生产订单子查询
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        public async Task<List<pro_ntity>> NtityIndex()
        {
            return await _pro_NtityService.Query();
        }

        /// <summary>
        /// 生产订单子添加
        /// </summary>
        /// <returns></returns> 

        [HttpPost]
        public async Task<IActionResult> NtityAdd(pro_ntity ntity)
        {
            if (ModelState.IsValid)
            {

                int result = await _pro_NtityService.Add(ntity);
                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }


        /// <summary>
        ///生产订单子修改
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpPut]
        public async Task<IActionResult> NtityUpdate(pro_ntity ntity)
        {
            if (ModelState.IsValid)
            {
                int result = await _pro_NtityService.Update(ntity);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }

        }

        /// <summary>
        /// 生产订单子删除
        /// </summary>
        /// <returns></returns> 

        [HttpDelete("{en_id}")]
        public async Task<IActionResult> NtityDelete(int en_id)
        {
            int result = await _pro_NtityService.Delete(en_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        /// <summary>
        ///子分页查询
        /// </summary>
        /// <returns></returns> 
        [HttpGet]
        public ActionResult<FenYe<pro_ntity>> NtityFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "en_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "pro_ntity"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<pro_ntity>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<pro_ntity> fenYe = new FenYe<pro_ntity>()
                {
                    ntitys = result,
                    Rows = row,
                };

                if (fenYe.ntitys.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }


        /// <summary>
        ///订单审核
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpPost("{po_id}")]
        public async Task<IActionResult> AuditSalesOrder(int po_id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var salesOrder = await myDbContext.pro_orders
                .Include(so => so.pro_ntitie) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.po_id == po_id);

            // 如果销售订单不存在或已经被逻辑删除，则返回错误信息
            // 检查从表sal_Orders是否有数据
            if (!salesOrder.pro_ntitie.Any() || salesOrder.pro_ntitie.All(order => order.IsDeleted))
            {
                return BadRequest("从表没有数据，不能进行审核");
            }
            // 检查从表pur_Purchase_Order是否有数据
            if (!salesOrder.pro_ntitie.Any())
            {
                return BadRequest("从表没有数据，不能进行审核");
            }
            try
            {
                // 审核销售订单
                salesOrder.AuditStatus = true;
                salesOrder.po_warehouse = '1';

                // 创建一个新的销售出库单对象
                // 创建一个新的销售出库单对象
                var salesOut = new pro_warehousing
                {
                    pw_id = 0, // 序号
                    pw_number = salesOrder.po_number, // 生产订单编号
                    pw_code = salesOrder.po_code,//客户姓名
                    pw_client_property = salesOrder.po_client_property,//客户属性
                    pw_types = salesOrder.po_types,//产品种类
                    pw_storage_date = DateTime.Now,//入库时间
                    pw_state = salesOrder.po_state,//订单状态
                    pw_warehouse = salesOrder.po_warehouse,//入库状态
                  //  AuditStatus = salesOrder.AuditStatus,//审核状态


                };
                // 将新的销售出库单添加到数据库
                myDbContext.pro_warehousing.Add(salesOut);
                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                int newOutId = salesOut.pw_id; // 获取自增的out_id

                // 遍历销售订单从表信息，为每条记录创建销售出库从表对象
                foreach (var order in salesOrder.pro_ntitie)
                {
                    var salesOutC = new pro_warehousing_from
                    {
                        wf_id = 0, // 序号
                        wf_sing_model = order.en_sing_model,//产品型号
                        wf_redserial_number = order.en_number,//产品名称
                        wf_redunit = order.en_redunit,//单位
                        wf_storage = (int)order.en_demanded,//数量
                        IsDeleted = false,
                        pro_warehousingpw_id = newOutId,
                    };
                    myDbContext.pro_warehousing_from.Add(salesOutC);
                }

                // 保存从表信息
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，并且已创建对应的采购入库单");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }
    }
}
